<template>
  <div id="ztree">
<!--    &nbsp;&nbsp;&nbsp;&nbsp;[ <a id="addLeaf" href="#" title="增加叶子节点" >增加叶子节点</a> ]-->
<!--    &nbsp;&nbsp;&nbsp;&nbsp;[ <a id="edit" href="#" title="编辑名称" >编辑名称</a> ]<br/>-->
<!--    &nbsp;&nbsp;&nbsp;&nbsp;[ <a id="remove" href="#" title="删除节点">删除节点</a> ]-->
<!--    [ <a id="clearChildren" href="#" title="清空子节点" >清空子节点</a> ]-->
    <ul id="treeDemo" class="ztree"></ul>
    <!--    鼠标右键弹出树菜单-->
    <ul class="widget-menu"  ref="rMenu" v-show="menushow" id="rmenu">
    <li class="widget-menu-item sharenew" ><span>新建</span><i class="el-icon-caret-right" style="position: absolute;top: 10px"></i>
      <ul class="widget-menu widget-sub-menu" style="top:0">
        <li class="widget-menu-item" @click="add(0,1)"><span>笔记</span></li>
        <li class="widget-menu-item"><span>Markdown</span></li>
        <li class="widget-menu-item"><span>模板笔记</span></li>
        <li class="widget-menu-item"><span>脑图</span></li>
        <li class="widget-menu-item" @click="add(1,1)"><span>文件夹</span></li>
      </ul>
      </li>
    <li class="widget-menu-item shareupload" ><span>上传</span><i class="el-icon-caret-right" style="position: absolute;top: 40px"></i>
      <ul class="widget-menu widget-sub-menu">
        <li class="widget-menu-item"><span>文件</span></li>
        <li class="widget-menu-item"><span>文件夹</span></li>
      </ul>
    </li>
      <li class="widget-menu-item split-line"></li>
      <li class="widget-menu-item" @click="edit"><span>重命名</span></li>
      <li class="widget-menu-item"><span>移动到</span></li>
      <li class="widget-menu-item"><span>复制</span></li>
      <li class="widget-menu-item"><span>粘贴</span></li>
      <li class="widget-menu-item" @click="removenode"><span>删除</span></li>
      <li class="widget-menu-item split-line"></li>
      <li class="widget-menu-item"><span>分享</span></li>
      <li class="widget-menu-item split-line"></li>
      <li class="widget-menu-item"><span>阅读密码</span></li>
    </ul>
  </div>
</template>

<script>
    import '../../plugins/zTree/js/jquery.ztree.all.js'
    import '../../plugins/zTree/js/jquery.ztree.exhide.js'
    let newCount=0;
    var rmenu=$(".widget-menu")
    export default {
        props:['newrootdoc'],
        name: "zTree",
        data(){
            return {
                menushow:false,
                setting: {
                    view: {
                        selectedMulti: false,
                        showLine:false
                    },
                    edit: {
                        enable: true,
                        showRemoveBtn: false,
                        showRenameBtn: false,
                        drag: {
                            isCopy: true,//能够复制
                            isMove: true,//能够移动
                            prev: true,//不能拖拽到节点前
                            next: true,//不能拖拽到节点后
                            inner: true//只能拖拽到节点中
                        }
                    },
                    data: {
                        keep: {
                            parent: true,
                            leaf: true
                        },
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pId",
                            rootPId: 0
                        }
                    },
                    callback: {
                        beforeDrag: this.beforeDrag,
                        beforeRename: this.beforeRename,
                        onRemove: this.onRemove,
                        beforeDrop:this.beforeDrop,
                        onClick: this.zTreeOnClick,
                        onRightClick:this.OnRightClick,
                        onRename:this.onRename//捕获重命名结束后的事件
                    }
                },
                zNodes: [
                    {id: 1, pid: 0, name: "父节点 1", open: true,folder:true,},
                    {id: 11, pid: 1, name: "叶子节点 1-1",isHidden:true},
                    {id: 12, pid: 1, name: "叶子节点 1-2",isHidden:true},
                    {id: 2, pid: 0, name: "父节点 2",folder:true},
                    {id: 13, pid: 2, name: "父节点 2-1",folder:true},
                    {id: 3, pid: 0, name: "父节点 3", open: true,folder:true},
                ]
            }
        },
        methods: {
            beforeDrag:function(treeId, treeNodes) {
                for (var i=0,l=treeNodes.length; i<l; i++) {
                    if (treeNodes[i].drag === false) {
                        return false;
                    }
                }
                return true;
            },
            beforeDrop:function(treeId, treeNodes, targetNode, moveType) {
                return targetNode ? targetNode.drop !== false : true;
            },
            onRemove:function(e, treeId, treeNode) {
            },
            beforeRename:function(treeId, treeNode, newName) {
                if (newName.length == 0) {
                    alert("节点名称不能为空.");
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    setTimeout(function(){zTree.editName(treeNode)}, 10);
                    return false;
                }
                return true;
            },
            onRename:function(event,treeId,treeNode){//传入被编辑的treeNode,
                // event、treeId不可删去，
                // 函数会按照参数序号抓取序号而非名字！，若写成function(treeNode){console.log(treeNode)}控制台则会打出event
                var _this=this;
                console.log(treeNode);
                this.$axios.put('/note/rename',{
                    noteId:treeNode.id,
                    noteTitle:treeNode.name
                }).then(function (res) {
                    console.log(res);
                    if(res.data.code===200){
                        _this.$parent.$refs.list.getnotelist();//重命名成功后刷新文件列表
                    }
                }).catch(function (err) {
                    console.log(err);
                })
            },
            add:function(e,notroot,type){
                var _this=this;
                //第一个参数若为1，表示添加文件夹，若为0，表示添加文件；第二个参数若为1，表示添加的东西的上级目录不是“我的文件”，若为0，表示添加的东西的上级目录是“我的文件”
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    isParent = e;//是否是文件夹
                if(notroot===1){//notroot=0时，表示添加pid=0的节点
                   var nodes = zTree.getSelectedNodes(),
                    treeNode = nodes[0];
                }
                if (treeNode) {//若pid!=0,添加入被选中的节点
                    var pId=treeNode.id;//获取被选中的节点id
                    if(isParent){//若是文件夹，则添加
                        _this.$axios.post('/note/folder/add',{
                            category:pId,
                            noteTitle:"新建文件夹",
                        }).then(function (res) {
                            if(res.data.code===200){
                                var id=res.data.data.noteId;
                                treeNode = zTree.addNodes(treeNode, {id:id, pId:pId, isParent:isParent, name:"新建文件夹"});
                                _this.zTreeOnClick(e.treeId,treeNode)
                                zTree.editName(treeNode[0]);
                            }
                        }).catch(function (err) {
                            console.log(err);
                        })
                    }else{//若是笔记，则添加并隐藏
                        _this.$axios.post('/note/add',{
                            //清空标题和内容框
                            content:'',
                            category:pId,
                            type:type,
                            noteTitle:"无标题笔记"
                        }).then(
                            function (res) {
                                if(res.data.code===200){
                                    var id=res.data.data.noteId;
                                    treeNode = zTree.addNodes(null, {id:id, pId:pId, isParent:isParent, name:"new node",isHidden:true});
                                    _this.$parent.editor.noteId=id;
                                    _this.zTreeOnClick(e.treeId,treeNode);
                                    _this.$parent.$refs.list.getnotelist();
                                    zTree.editName(treeNode[0]);
                                }
                            }
                        ).catch(function (err) {
                            console.log(err);
                        })
                        treeNode = zTree.addNodes(treeNode, {id:(100 + newCount), pId:0, isParent:isParent, name:"new node",isHidden:true});
                    }
                } else {//添加入“我的文件夹”
                    if(isParent){//若是文件夹，则添加
                        _this.$axios.post('/note/folder/add',{
                            category:0,
                            noteTitle:"新建文件夹"
                        }).then(function (res) {
                            console.log(res);
                            if(res.data.code===200){
                                var id=res.data.data.noteId;
                                treeNode = zTree.addNodes(null, {id:id, pId:0, isParent:isParent, name:"新建文件夹"});
                                _this.zTreeOnClick(e.treeId,treeNode);
                                zTree.editName(treeNode[0]);
                            }
                        }).catch(function (err) {
                            console.log(err);
                        })
                    }else{//若是笔记，则添加并隐藏
                        _this.$axios.post('/note/add',{
                            content:'',
                            category:0,
                            noteTitle:"无标题笔记",
                            type:type,
                        }).then(
                            function (res) {
                                if(res.data.code===200){
                                    var id=res.data.data.noteId;
                                    treeNode = zTree.addNodes(null, {id:id, pId:0, isParent:isParent, name:"new node",isHidden:true});
                                    _this.zTreeOnClick(e.treeId,treeNode);
                                    _this.$parent.editor.noteId=id;
                                    _this.$parent.$refs.list.getnotelist();
                                    zTree.editName(treeNode[0]);
                                }
                            }
                        ).catch(function (err) {
                            console.log(err);
                        })

                    }
                }
                // if (treeNode) {
                //     zTree.editName(treeNode[0]);
                // } else {
                //     alert("不能为笔记增加子节点哦");
                // }
                this.hideMenu();
            },
            edit:function(){
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),//获取当前树
                    nodes = zTree.getSelectedNodes(),//获取当前节点
                    treeNode = nodes[0];
                if (nodes.length == 0) {
                    alert("请先选择一个节点");
                    return;
                }
                zTree.editName(treeNode);
                this.hideMenu();
            },
            removenode:function(e) {
                var _this=this;
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    nodes = zTree.getSelectedNodes(),
                    treeNode = nodes[0];
                if (nodes.length == 0) {
                    alert("请先选择一个节点");
                    return;
                }
                var callbackFlag = $("#callbackTrigger").attr("checked");
                zTree.removeNode(treeNode, callbackFlag);

                this.$axios.delete('/note/delete',{
                    data:{
                        noteId:treeNode.id
                    }
                }).then(function (res) {
                    console.log(res);
                    if (res.data.code==200){
                        _this.$parent.$refs.list.getnotelist();//删除成功后刷新文件列表
                    }
                }).catch(function (err) {
                    console.log(err);
                })
                this.hideMenu();
            },
            clearChildren:function(e) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    nodes = zTree.getSelectedNodes(),
                    treeNode = nodes[0];
                if (nodes.length == 0 || !nodes[0].isParent) {
                    alert("请先选择一个父节点");
                    return;
                }
                zTree.removeChildNodes(treeNode);
            },
            //使得folder=true的节点样式变成文件夹
            fixIcon(){
                var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                //过滤出folder属性为true的节点
                var folderNode = treeObj.getNodesByFilter(function (node) { return node.folder});
                // var hiddenNode=treeObj.getNodesByFilter(function (node) {return node.isHidden==null});
                for(var j=0 ; j<folderNode.length; j++){//遍历过滤出的节点，设置其isParent属性为true;
                    folderNode[j].isParent = true;
                }
                // for(var i=0;i<hiddenNode.length;j++){
                //     hiddenNode[i].isHidden=true;
                // }
                treeObj.refresh();//调用api自带的refresh函数。
            },
            zTreeOnClick(e,treeId,treeNode){//点击子节点触发方法
                 this.$emit('checkedNode',treeNode)
            },

            OnRightClick(event, treeId, treeNode) {
                var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                if (!treeNode) {
                    treeObj.cancelSelectedNode();
                    this.showRMenu("root", event.clientX, event.clientY);
                } else if (treeNode && !treeNode.noR) { //noR属性为true表示禁止右键菜单
                    if (treeNode.newrole && event.target.tagName != "a" && $(event.target).parents("a").length == 0) {
                        treeObj.cancelSelectedNode();
                        this.showRMenu("root", event.clientX, event.clientY);
                    } else {
                        treeObj.selectNode(treeNode);
                        this.showRMenu("node", event.clientX, event.clientY);
                    }
                }
            },
            showRMenu(type,x,y){
                //用jquery设置css会毁坏原本的样式
                // $(".widget-menu").css({"top":y+"px", "left":x+"px", "visibility":"visible"});
                //在此用vue的$refs设置位置可保全原本样式
                this.$refs.rMenu.style.left=x+"px";//子菜单出现的位置设置
                this.$refs.rMenu.style.top=y+"px";
                this.menushow=true;
                $("body").bind("mousedown",this.onBodyMouseDown);//为body绑定鼠标点击事件
            },
            onBodyMouseDown(event){
                var _this=this;
                if (!(event.target.id == "rmenu"||$(event.target).parents("#rmenu").length>0)){//当点击id为rmenu及其子元素以外的地方时使菜单隐藏
                    _this.hideMenu();
                }
            },
            hideMenu(){
                 this.menushow=false;//隐藏菜单函数
            },
            refreshTree(){
                var _this=this;
                this.$axios.get('/note/queryValid', {
                    withCredentials:true,
                    params: {
                    }
                }).then(function (response) {
                    console.log(response)
                    _this.zNodes=response.data.data.data;
                })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            adddc(){

            },
            addfile(){
            },
            refresh() {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.refresh();
                this.$parent.checkNode.id = 0;
            }
        },
        watch:{
            zNodes:function (val) {
                $.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes);
                this.fixIcon()
            }
        },
        mounted(){
            var _this=this;
            this.$nextTick(function () {
                $.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes);
                this.fixIcon();
                $("#addParent").bind("click", {isParent:true}, this.add);
                $("#addLeaf").bind("click", {isParent:false}, this.add);
                $("#edit").bind("click", this.edit);
                $("#remove").bind("click", this.removenode);
                $("#clearChildren").bind("click",this.clearChildren);
            })
           this.refreshTree();
        },
    }
</script>
<style>
  @import '../../plugins/zTree/css/zTreeStyle/zTreeStyle.css';
  #ztree{
    width: 100%;
  }

  .widget-menu{
    display: inline-block;
    width: 125px ;
    background: #ffffff;
    z-index: 1000;
    position: absolute;
    left: 25px;
    top: 50px;
    box-shadow: 0px 1px 16px 0 rgba(90, 109, 122, 0.41);
    padding: 0;
    border-radius: 0;
  }
  .widget-menu .widget-menu-item{
    display: inline-block;
    float: left;
    width: 100%;
    cursor: pointer;
    height: 30px;
    color: #999;
    font-size: 12px;

  }
  .widget-menu .widget-menu-item span{
    display: inline-block;
    float: left;
    position: relative;
    top: 25%;
    margin-left: 20px;
    /*覆写行高以避免继承父元素行高*/
    line-height: 100%;
  }
  .widget-menu .widget-menu-item:hover{
    background: #ebf3fd;
    color: #7ab2f3;
  }
  .split-line{
    height: 0 !important;
    border-bottom:#ebf3fd solid 1px;
  }
  .widget-sub-menu{
    position: absolute;
    left: 121px;
    top:31px;
    display: none;
  }
  .widget-sub-menu li span{
    display: inline-block;
    float: left;
    position: relative;
    top: 25%;
    margin-left: 20px;
  }
  .acc-set:hover .widget-sub-menu{
    display: inline-block;
  }
  .sharenew:hover .widget-sub-menu{
    display: inline-block;
  }
  .shareupload:hover .widget-sub-menu{
    display: inline-block;
  }
</style>
